<template>
  <div class="page">
    <div class="topSearch">
      <div class="title">
        <span
          style="
            width: 3px;
            height: 20px;
            background-color: #0f79e2;
            margin-right: 8px;
          "
        ></span
        ><span>调货列表</span>
      </div>
      <div class="search">
        <span>调货单名：</span>
        <el-input
          size="small"
          clearable
          style="width: 250px"
          v-model="allotName"
          placeholder="请输入"
        ></el-input>
        <span>调出仓库：</span>
        <el-select
          clearable
          v-model="outAreaId"
          size="small"
          style="width: 250px"
          placeholder="请选择"
        >
          <el-option
            v-for="item in warehouseList"
            :key="item.area"
            :label="item.areaName"
            :value="item.area"
          />
        </el-select>
        <el-button
          size="small"
          type="primary"
          style="width: 80px; margin-left: 20px"
          @click="getAllotMaterial"
          >查询
        </el-button>
        <el-button
          size="small"
          style="width: 80px; margin-left: 20px"
          @click="reset"
          >重置
        </el-button>
        <el-button
          size="small"
          type="primary"
          style="width: 100px; position: absolute; right: 40px"
          @click="addProduct"
        >
          新增调货单
        </el-button>
      </div>
    </div>
    <div class="centerTable">
      <el-table
        :data="purchaseData"
        border
        height="calc(100vh - 350px)"
        :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
        v-loading="loading"
        :headerCellStyle="{
          textAlign: 'center',
          fontWeight: 400,
          background: '#66b1ff',
          color: 'white',
        }"
      >
        <el-table-column prop="allotNo" label="调货单号" width="140px" />
        <el-table-column prop="allotName" label="单名" />
        <el-table-column label="产品明细" width="550px">
          <template slot-scope="scope">
            <el-table
              :data="scope.row.list"
              maxHeight="250px"
              :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
              :headerCellStyle="{
                textAlign: 'center',
                fontWeight: 400,
                background: '#66b1ff',
                color: 'white',
              }"
              border
              style="width: 100%"
            >
              <el-table-column prop="productCode" label="编码" />
              <el-table-column prop="productName" label="产品" width="200px" />
              <el-table-column prop="norms" label="规格" />
              <el-table-column prop="singleNum" label="数量" />
<!--              <el-table-column prop="warehousePosition" label="出库-->
<!--              库位" />-->
            </el-table>
          </template>
        </el-table-column>
        <el-table-column label="入库凭证">
          <template slot-scope="scope">
            <el-image
              v-for="(v, i) in scope.row.inProof"
              :key="i"
              style="width: 50px; height: 50px"
              ref="preview"
              :src="host + v"
              :preview-src-list="[host + v]"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="出库凭证">
          <template slot-scope="scope">
            <el-image
              v-for="(v, i) in scope.row.outProof"
              :key="i"
              style="width: 50px; height: 50px"
              ref="preview"
              :src="host + v"
              :preview-src-list="[host + v]"
            >
            </el-image>
            <el-link
              v-if="!scope.row.outProof"
              style="
                color: steelblue;
                cursor: pointer;
                margin-top: 10px;
                text-decoration: none;
              "
              @click="upload(scope.row, 2)"
              >上传凭证
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="调出仓库" width="90px">
          <template slot-scope="scope">
            <div v-if="scope.row.outAreaId === 56"><span>西安2仓</span></div>
            <div v-if="scope.row.outAreaId === 58"><span>山西仓</span></div>
          </template>
        </el-table-column>
        <el-table-column label="调出联系方式" width="80px">
          <template slot-scope="scope">
            {{ scope.row.outAreaPeopleName + scope.row.outAreaPhone }}
          </template>
        </el-table-column>
        <el-table-column label="调入仓库" width="0px">
          <template slot-scope="scope">
            <div v-if="scope.row.inAreaId === 56"><span>西安2仓</span></div>
            <div v-if="scope.row.inAreaId === 58"><span>山西仓</span></div>
          </template>
        </el-table-column>
        <el-table-column label="调入联系方式" width="90px">
          <template slot-scope="scope">
            {{ scope.row.inAreaPeopleName + scope.row.inAreaPhone }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="createTime" label="创建时间" width="90px" />
        <el-table-column prop="outInventory" label="是否入库" width="60px">
          <template slot-scope="scope">
            <span v-if="scope.row.inInventory == 0" style="color: #2cb5e8"
              >未入库</span
            >
            <span v-if="scope.row.inInventory == 1" style="color: #ebb563"
              >已入库</span
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" >
          <template slot-scope="scope">
            <div style="display: flex; flex-direction: column">
              <el-link
                v-if="scope.row.inInventory !== 1"
                @click="editOutport(scope.row)"
                style="
                  color: #0f79e2;
                  width: auto;
                  background-color: #e7f1fc;

                  cursor: pointer;
                  text-decoration: none;
                "
              >
                编辑
              </el-link>
              <el-link
                v-if="scope.row.inInventory !== 1"
                style="
                  color: #f5b330;
                  width: auto;
                   margin-top: 5px;
                  background-color: #fef7ea;
                  cursor: pointer;
                "
                @click="upload(scope.row, 1)"
                >确认完成
              </el-link>
              <el-link
                @click="exportItem(scope.row)"
                style="
                  color: #0f79e2;
                  width: auto;
                   margin-top: 5px;
                  background-color: #e7f1fc;
                  cursor: pointer;
                  text-decoration: none;
                "
              >
                导出
              </el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      style="padding: 20px 0"
      align="right"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[20, 30, 40, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
    >
    </el-pagination>
    <!--    分割线--><!--    分割线--><!--    分割线--><!--    分割线--><!--    分割线--><!--    分割线--><!--    分割线-->
    <el-dialog :close-on-click-modal="false"
      :title="title"
      :visible.sync="addDialog"
      width="60%"
      center
      :show-close="false"
      :before-close="handleClose"
    >
      <div style="display: flex; align-items: center; margin-bottom: 30px">
        <div style="width: 80px; text-align: center">
          <span style="color: red">*</span>单名：
        </div>
        <el-input
          size="small"
          v-model="addForm.allotName"
          style="width: 36%"
        ></el-input>
        <div style="width: 80px; text-align: center; margin-left: 20px">
          备注：
        </div>
        <el-input
          size="small"
          v-model="addForm.remark"
          style="width: 36%"
        ></el-input>
      </div>
      <div style="display: flex; align-items: center; margin-bottom: 30px">
        <div style="width: 80px; text-align: center">
          <span style="color: red">*</span>调出仓库：
        </div>
        <el-select
          clearable
          v-model="addForm.outAreaId"
          size="small"
          :disabled="disabled"
          style="width: 36%"
          placeholder="请选择"
          @change="changeFactoryInventory"
        >
          <el-option
            v-for="item in allWarehouseList"
            :key="item.area"
            :label="item.areaName"
            :value="item.area"
          />
        </el-select>
        <div style="width: 80px; text-align: center; margin-left: 20px">
          <span style="color: red">*</span>调入仓库：
        </div>
        <el-select
          clearable
          v-model="addForm.inAreaId"
          size="small"
          :disabled="disabled"
          style="width: 36%"
          placeholder="请选择"
        >
          <el-option
            v-for="item in warehouseList"
            :key="item.area"
            :label="item.areaName"
            :value="item.area"
          />
        </el-select>
      </div>
      <el-table
        :data="factoryInventoryData"
        border
        max-height="300px"
        :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
        :headerCellStyle="{
          textAlign: 'center',
          fontWeight: 400,
          background: '#66b1ff',
          color: 'white',
        }"
      >
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="productCode" label="产品编码" />
        <el-table-column prop="norms" label="规格" />
        <el-table-column prop="count" label="当前库存" />
        <el-table-column prop="purchaseNum" label="调货数量">
          <template slot-scope="scope">
            <el-input-number
              :min="0"
              v-model="scope.row.singleNum"
              @change="countChange"
              size="small"
            ></el-input-number>
          </template>
        </el-table-column>
<!--        <el-table-column prop="purchaseNum" label="调入库位">-->
<!--          <template slot-scope="scope">-->
<!--           <el-select v-model="scope.row.warehousePosition"   filterable-->
<!--                      placeholder="请选择" size="small">-->
<!--             <el-option-->
<!--                 v-for="item in positionList"-->
<!--                 :key="item"-->
<!--                 :value="item"-->
<!--                 :label="item"-->
<!--             >-->
<!--             </el-option>-->
<!--           </el-select>-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="outPic" :title="uploadTitle" :close-on-click-modal="false">
      <div style="display: flex; align-items: center; margin-bottom: 50px">
        <!--        <div style="width:100px;text-align: center;margin-top: 30px">凭：</div>-->
        <div>
          <span style="color: gray; font-size: 12px"
            >(粘贴复制即可上传图片)</span
          >
          <div class="div" style="display: flex; align-items: center">
            <div
              v-for="(v, i) in preSalesImg"
              style="display: flex; align-items: center; margin-right: 10px"
            >
              <el-image
                :key="i"
                style="width: 50px; height: 50px"
                ref="preview"
                :src="host + v"
                :preview-src-list="[host + v]"
              >
              </el-image>
              <div @click="deletePic(i)">
                <el-icon name="delete"></el-icon>
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="outPic = false">取 消</el-button>
        <el-button type="primary" @click="submitOutPic">确 定</el-button>
      </span>
      <span slot="footer" class="dialog-footer">
        <span style="display: block; color: red" v-if="uploadType == 1"
          >*确定后此调货单完成并且结束调货流程</span
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import axios from 'axios';
import Decimal from 'decimal.js';
import dayjs from 'dayjs';
import * as XLSX from 'xlsx-js-style';
import store from "../../store";

export default {
  data () {
    return {
      pageSize: 20,
      currentPage: 1,
      outPic: false,
      uploadTitle: "",
      pageNumber: 1,
      allotName: "",
      factoryId: "",
      optionType: "",
      areaId: "",
      outAreaId: "",
      title: "",
      disabled: false,
      startTime: "",
      outPreviewImg: [],
      endTime: "",
      productCode: "",
      productId: "",
      totalCount: 0,
      host: this.$imgHost,
      warehouseId: "",
      factoryName: "",
      uploadType: "",
      sateValue: "",
      editSingleId: "",
      loading: false,
      allCount: "",
      addDialog: false,
      addForm: {},
      warehouseList: [],
      positionList: [],
      inPreSalesImg: [],
      preSalesImg: [],
      preSalesImgList: [],
      inPreSalesImgList: [],
      inPreviewImg: [],
      previewImg: [],
      factoryList: [],
      allWarehouseList: [],
      purchaseData: [],
      factoryInventoryData: []
    }
  },
  created () {
    document.addEventListener('paste', this.handlePaste)
    const params = {
      pageSize: 100000,
      pageNumber: 1
    }
    this.$api.areaLedgerAreaList(params).then(res => {
      this.warehouseList = res
    })
    this.$api.inventoryGetLocationName().then(res => {
      this.positionList = res
    })
    this.$api.areaLedgerAreaListNew(params).then(res => {
      this.allWarehouseList = res
    })
    this.$api.factoryGetFactoryList().then(res => {
      this.factoryList = res
    })
    this.getAllotMaterial()
  },
  methods: {
    exportItem (val) {
      try {
        const data = val.list.map(a => ({
          编码: a.productCode,
          产品: a.productName,
          // 调出库位: a.warehousePosition,
          规格: a.norms,
          数量: a.singleNum,
        }));
        const sheetName = val.singleName + '产品明细';
        const wb = XLSX.utils.book_new();
        const sheet = XLSX.utils.json_to_sheet(data);
        sheet['!cols'] = [
          { wpx: 100 }, // 编码
          { wpx: 200 }, // 产品
          { wpx: 100 }, // 规格
          { wpx: 100 }, // 数量
        ];
        XLSX.utils.book_append_sheet(wb, sheet, sheetName);
        const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
        const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `${val.allotName}产品明细${new Date().getTime()}.xlsx`;
        link.click();
        URL.revokeObjectURL(link.href);
      } catch (error) {
        console.error('Error generating inventory report:', error);
      }
      function s2ab (s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i < s.length; ++i) {
          view[i] = s.charCodeAt(i) & 0xFF;
        }
        return buf;
      }
    },
    handleChange (val) {
    },
    handleClose () {
    },
    changeFactoryInventory (val) {
      this.$api.inventoryGetInventoryGoodsList({ areaId: val }).then(res => {
        if (res) {
          res.forEach(el => {
            el.singleNum = 0
            // el.warehousePosition=""
          })
        }
        this.factoryInventoryData = res
      })
    },
    selectTime (val) {
      if (val) {
        this.startTime = dayjs(val[0]).format("YYYY-MM-DD");
        this.endTime = dayjs(val[1]).format("YYYY-MM-DD");
      } else {
        this.startTime = ''
        this.endTime = ''
      }
    },
    //操作入库
    optionPutInventory (val) {
      console.log(val)
      const data = {
        singleNo: val.singleNo,
        areaId: val.areaId
      }
      this.$api.singleSingleOutInventory(data).then(res => {
        if (res === 1) {
          this.$message({ message: "操作成功", type: "success" })
          this.getAllotMaterial()
        }
      })
    },
    //单品出库列表
    getAllotMaterial () {
      this.loading = true
      const data = {
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        outAreaId: this.outAreaId,
        allotName: this.allotName,
        startTime: this.startTime,
        endTime: this.endTime
      }
      this.$api.allotGetAllotMaterial(data).then(res => {
        res.data.forEach(el => {
          if (el.outProof) {
            el.outProof.forEach(val => {
              this.outPreviewImg.push('https://' + val)
            })
          }
          if (el.inProof) {
            el.inProof.forEach(val => {
              this.inPreviewImg.push('https://' + val)
            })
          }
        })
        this.loading = false
        this.purchaseData = res.data
        this.totalCount = res.total
      })
    },
    submit () {
      if (!this.addForm.allotName || !this.addForm.inAreaId || !this.addForm.outAreaId) {
        return this.$message({ message: "请检查必填项！" })
      }
      this.addForm.createTime = dayjs(this.addForm.createTime).format("YYYY-MM-DD")
      // const filteredList = this.factoryInventoryData.filter(item => item.purchaseNum !== 0 && item.warehousePosition);  //采购数量和库位必填
      const filteredList = this.factoryInventoryData.filter(item => item.singleNum !== 0); //采购数量必填，库位非必填
      const selectedFieldsArray = filteredList.map(product => ({
        materialId: product.materialId,
        productCode: product.productCode,
        productName: product.productName,
        singleNum: product.singleNum,
        norms: product.norms,
        // warehousePosition: product.warehousePosition,
        inAreaId: this.addForm.inAreaId,
      }));

      if (this.optionType == 1) {
        const data = {
          ...
          this.addForm,
          list: selectedFieldsArray,
        }
        this.$api.allotAddAllotMaterial(data).then(res => {
          if (res) {
            this.$message({ message: "新增成功", type: "success" })
            this.addDialog = false
            this.getAllotMaterial()
          }
        })
      } else if (this.optionType == 2) {
        const data = {
          ...
          this.addForm,
          list: selectedFieldsArray,
          singleNo: this.editSingleId
        }
       return console.log(data,"data")
        this.$api.allotUpdateAllotMaterial(data).then(res => {
          if (res) {
            this.$message({ message: "操作成功", type: "success" })
            this.addDialog = false
            this.getAllotMaterial()
          }
        })
      }

    },
    addProduct () {
      this.addDialog = true
      this.title = "新增调货单"
      this.disabled = false
      this.optionType = 1
      this.addForm = this.$options.data.call(this).addForm
      this.factoryInventoryData = []
    },
    handlePaste (event) {
      if (!this.outPic) return;
      const clipboardData = event.clipboardData || window.clipboardData;
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i];

          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile();
            if (file) {
              this.uploadImage(file);
            }
          } else {
            this.$message.error('请拷贝图片!');
            break;
          }
        }
      }
    },
    uploadImage (imageFile) {
      const formData = new FormData();
      formData.append('file', imageFile);
      axios.post(`${this.$apiHost}/common/fileImgUrl`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'token':store.state.token
        }
      })
        .then(response => {
          this.preSalesImg.push(response.data.result[0]);
          // this.preSalesImgList.push('https://' + response.data.result[0]);
        })
        .catch(error => {
        });
    },
    deletePic (i) {
      this.preSalesImg.splice(i, 1)
    },
    handleSizeChange (val) {
      this.pageSize = val
      this.getAllotMaterial()
    },
    handleCurrentChange (val) {
      this.pageNumber = val
      this.getAllotMaterial()
    },
    reset () {
      this.pageSize = 20
      this.pageNumber = 1
      this.areaId = ''
      this.allotName = ''
      this.startTime = ''
      this.endTime = ''
      this.getAllotMaterial()
    },
    editOutport (row) {
      this.title = '编辑'
      this.optionType = 2
      this.disabled = true
      this.addDialog = true
      this.editSingleId = row.singleNo
      this.addForm = {
        allotName: row.allotName,
        allotNo: row.allotNo,
        remark: row.remark,
        inAreaId: row.inAreaId,
        outAreaId: row.outAreaId
      }
      this.$api.inventoryGetInventoryGoodsList({ areaId: row.outAreaId }).then(res => {
        //将接口返回的产品数量替换成row的数量
        res.forEach(el => {
          let match = row.list.find(val => val.productName === el.productName);
          if (match) {
            el.singleNum = match.singleNum
            // 标记替换的数据
            el.replaced = true;
          } else {
            el.singleNum = 0
            //false为不标记
            el.replaced = false;
          }
        })
        //将row.singleNum替换过的数据排在列表的前面
        res.sort((a, b) => b.replaced - a.replaced);
        this.factoryInventoryData = res
      })
    },
    countChange () {
      this.factoryInventoryData.forEach(el => {
        if (el.singleNum > el.count) {
          this.$message({ message: "调货数量不能大于工厂库存" })
        }
        if (!el.singleNum) {
          el.singleNum = 0
        }
      })
    },
    upload (val, type) {
      this.preSalesImg = []
      this.outPic = true
      this.outWarehouseId = val.allotNo
      // type2调出
      this.uploadType = type
      if (type == 2) {
        this.uploadTitle = "上传调出凭证"
        if (val.outProof) {
          val.outProof.forEach(el => {
            this.preSalesImgList.push(this.host + el)
          })
          this.preSalesImg = val.outProof
        }
        //  type1 调入
      } else if (type == 1) {
        this.uploadTitle = "确认调货及上传调入凭证"
        this.outPic = true
        if (val.inProof) {
          val.inProof.forEach(el => {
            this.preSalesImgList.push(this.host + el)
          })
          this.preSalesImg = val.inProof
        }
      }
    },
    //上传调入和调出图片
    submitOutPic () {
      if (this.uploadType == 2) {
        const data = {
          allotNo: this.outWarehouseId,
          outProof: this.preSalesImg,
        }
        this.$api.allotUpdateOutProofByAllotNo(data).then(res => {
          if (res) {
            this.$message({ message: "操作成功", type: "success" })
            this.outPic = false
            this.getAllotMaterial()
          }
        })
      } else if (this.uploadType == 1) {
        const data = {
          allotNo: this.outWarehouseId,
          inProof: this.preSalesImg
        }
        this.$api.allotAllotOutAndInInventory(data).then(res => {
          if (res) {
            this.$message({ message: "操作成功", type: "success" })
            this.outPic = false
            this.getAllotMaterial()
          }
        })
      }
    }
  }
}


</script>
<style lang='less' scoped>
.title {
  display: flex;
  margin-left: 20px;

  span {
    display: flex;
    margin-top: 20px;
  }
}

.topSearch {
  width: 100%;
  height: 110px;
  box-shadow: inset 0 20px 10px rgba(0, 128, 255, 0.2);
  border-bottom: 1px solid rgba(0, 128, 255, 0.08);

  .search {
    display: flex;
    align-items: center;
    margin-top: 15px;

    span {
      margin-left: 20px;
    }
  }
}

.centerTable {
  margin-top: 20px;
}

.warehouseTag {
  display: flex;
  justify-content: center;
  height: 30px;
  //width: 120px;
  margin: 0 28px 0 28px;
  align-items: center;
  border-radius: 50px;
}

.warehouse_icon {
  width: 20px;
  height: 20px;
  margin-right: 3px;
}

/deep/ .el-dialog__header {
  background-color: #0f79e2;
  //border-top-left-radius: 20px;
  //border-top-right-radius: 20px;
}

/deep/ .el-dialog__title {
  color: #fff;
}

/deep/ .center {
  border-radius: 20px;
}

/deep/ .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}
</style>
